package com.study.english.scheduled;


import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.study.english.domain.SysVideo;
import com.study.english.domain.SysVideoType;
import com.study.english.service.ISysVideoService;
import com.study.english.service.ISysVideoTypeService;
import com.study.english.util.CronUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class ScheduledTask {
    @Autowired
    private ISysVideoTypeService sysVideoTypeService;
    @Autowired
    private ISysVideoService sysVideoService;

    // 视频替换（每天点执行）
    @Scheduled(cron = "0 5 0 * * *")
    public void sysVideoTask() {
        Date date = new Date();
        List<SysVideoType> sysVidoeTypeList = sysVideoTypeService.list(new QueryWrapper<SysVideoType>().eq("study_flag", 1).isNotNull("cron_tab"));
        for (SysVideoType vo : sysVidoeTypeList) {
            String cronTab = vo.getCronTab();
            List<Date> nextExecDate = CronUtil.getNextExecDate(cronTab, 2);
            Date nextDate = nextExecDate.get(0);
            if (DateUtil.isSameDay(nextDate, date)) {
                SysVideo sysVideoCurr = sysVideoService.getOne(new QueryWrapper<SysVideo>().orderByDesc("sort_num").eq("status", 1).eq("video_type_id", vo.getId()).last("limit 1"));
                Integer sortNum = 0;
                if (sysVideoCurr != null && sysVideoCurr.getSortNum() != null) {
                    sortNum = sysVideoCurr.getSortNum();
                }
                List<SysVideo> sysVideoList = sysVideoService.list(new QueryWrapper<SysVideo>().gt("sort_num", sortNum).orderByAsc("sort_num").eq("status", 0).eq("video_type_id", vo.getId()).last("limit " + vo.getStudyNum()));
                if (sysVideoList == null || sysVideoList.size() == 0) {
                    continue;
                }
                sysVideoService.update(new UpdateWrapper<SysVideo>().set("status", 2).eq("status", 1).eq("video_type_id", vo.getId()).set("modify_time",date));
                for (SysVideo sysVideo : sysVideoList) {
                    sysVideo.setStatus(1);
                    sysVideo.setModifyTime(date);
                }
                sysVideoService.updateBatchById(sysVideoList);
            }
        }
        log.info("");
    }
}
